package cn.dubito.miaosha.config;

import cn.dubito.miaosha.domain.SeckillUser;
import cn.dubito.miaosha.service.SeckillUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liliang
 * @description: 参数解析器
 * @date 2018/3/31.
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private SeckillUserService userService;

    /**
     * 判断参数类型
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz = methodParameter.getParameterType();
        return clazz == SeckillUser.class;
    }


    /**
     * 解析 方法参数
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
//        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
//        String paramToken = request.getParameter(SeckillUserService.COOKIE_NAME_TOKEN);
//        String cookieToken = getCookieValue(request, SeckillUserService.COOKIE_NAME_TOKEN);
//        boolean cookieIsNull = StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken);
//        if (cookieIsNull) {
//            return null;
//        }
//        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        return UserContext.getUser();
    }

//    /**
//     * 获取 Cookie 里对应的值
//     *
//     * @param request
//     * @param cookieName
//     * @return
//     */
//    private String getCookieValue(HttpServletRequest request, String cookieName) {
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if (cookieName.equals(cookie.getName())) {
//                return cookie.getValue();
//            }
//        }
//        return null;
//    }
}
